package com.cg.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@CrossOrigin
@RestController
@Api(value = "fileController",description = "欢迎来到文件上传",tags = "文件上传")
@Slf4j
@RequestMapping("/api/file")
public class FileController {
    @Value("${web.upload-path}")
    private String uploadPath;

    @ApiOperation("文件上传")
    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public String upload(@RequestPart("file") MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String uniqueFileName = UUID.randomUUID().toString() + fileExtension;
        String visibleUri = "/" + uniqueFileName;
        String saveUri = uploadPath + "/" + uniqueFileName;

        log.info("图片原文件名={} 图片访问地址={} 图片保存真实地址={}", originalFilename, visibleUri, saveUri);

        File saveFile = new File(saveUri);
        try {
            file.transferTo(saveFile);
        } catch (IOException e) {
            log.error("文件上传失败", e);
            throw new IOException("文件上传失败", e);
        }

        return visibleUri;
    }
}